package com.project.pet.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.project.pet.common.Constant;
import com.project.pet.common.ResponseData;
import com.project.pet.mapper.UserMapper;
import com.project.pet.pojo.User;
import com.project.pet.utils.ResponseDataUtil;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommonService {
    @Autowired
    private UserMapper userMapper;

    public <T> List<Map<String,Object>> addUsernameToRes(List<T> list,String [] keys){
        List<Map<String, Object>> res = new ArrayList<>();
        for (Object o : list) {
            Map<String,Object> map = JSON.parseObject(JSON.toJSONString(o), Map.class);
            for (String key : keys) {
                if(!StringUtils.isEmpty(map.get(key))){
                    Integer userId = Integer.parseInt(String.valueOf(map.get(key)));
                    User user = userMapper.selectByPrimaryKey(userId);
                    if(user!=null){
                        map.put(key+"ToName",user.getUsername());
                    }
                }
            }
            res.add(map);
        }
        return res;
    }

    public ResponseData<Object> upload(String base64) {
        String newName = IdUtil.simpleUUID()+".jpg";
        HashMap<String, String> data = new HashMap<>();
        data.put("src", Constant.FILE_URL_PREFIX+newName);
        Boolean isSuccess = decryptByBase64(base64, Constant.FILE_HOME + newName);
        if(isSuccess)
            return ResponseDataUtil.buildSuccess(data);
        return ResponseDataUtil.buildError("文件上传失败");
    }




    public static Boolean decryptByBase64(String base64, String filePath) {
        if (Strings.isNullOrEmpty(base64) || Strings.isNullOrEmpty(filePath)) {
            return Boolean.FALSE;
        }
        try {
            Files.write(Paths.get(filePath),
                    Base64.decodeBase64(base64.substring(base64.indexOf(",") + 1)), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
